<template>
    <Layout>
        <div v-if="!detailShow" v-show="!detailShow">
            <Form :label-width="120" :model="formInline">
                <Row class="query-form">
                    <Col span="8">
                        <FormItem label="试卷名称：" prop="paperInfo">
                            <Input v-model="formInline.paperInfo"/>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="所属单位：">
                            <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId1" @setOrgname="setOrgName1"
                                         :rootOrgId="companyId"
                                         :orgTree="true"></cascaderDom>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <Button @click="cancel" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                    </Col>
                </Row>
            </Form>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addModel">新增</Button>
                </Col>
            </Row>
            <Table ref='table' :loading="loading" border :columns="paperColumns"
                   :data="paperData" no-data-text="没有查询到相关数据!" :height="tableHeight" highlight-row stripe
                   size="small"></Table>
            <Row style="margin-right:10px;">
                <Col span="24">
                    <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                          @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray"
                          show-total show-sizer show-elevator/>
                </Col>
            </Row>

            <Modal v-model="modal1" title="试卷配置" :width="900" :transfer=false>
                <Form :label-width="140" ref="formCustom" :model="form1data" :rules="ruleCustom" :class="mode === 'view'?'modal-view-detail':'modal-form'">
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="12">
                            <FormItem label="试卷名称：" prop="paperInfo">
                                <div v-if="mode === 'view'">{{form1data.paperInfo}}</div>
                                <Input v-model="form1data.paperInfo" show-word-limit :maxlength="100" v-else placeholder="请输入..."/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="试卷类型：" prop="paperType">
                                <div v-if="mode === 'view'">{{form1data.paperType}}</div>
                                <Input v-model="form1data.paperType" show-word-limit :maxlength="100" v-else
                                       placeholder="请输入..."/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="12">
                            <FormItem label="所属公司：" prop="companyId">
                                <div v-if="mode === 'view'">{{form1data.companyName}}</div>
                                <cascaderDom v-else ref="childOrg"
                                             @setOrgInfo='setOrgId'
                                             @setOrgname='setOrgName'
                                             :currentOrgId="form1data.companyId"
                                             :currentOrgName="form1data.companyName"
                                             :orgTree="true" :rootOrgId="companyId"></cascaderDom>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="题库选择：" prop="bsaeQstInfo">
                                <div v-if="mode === 'view'">{{form1data.bsaeQstInfo}}</div>
                                <Input type="text" v-model="form1data.bsaeQstInfo" placeholder="请选择题库..." v-else
                                       @click.native="openQuestionBase"></Input>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="12">
                            <FormItem label="考试日期：" prop="examDate">
                                <div v-if="mode === 'view'">{{this.renderViewDateArr(form1data.examDate)}}</div>
                                <DatePicker v-model="form1data.examDate" format="yyyy-MM-dd" type="daterange"
                                            placement="bottom-end" placeholder="请选择考试日期"
                                            v-else
                                            :options="{disabledDate(date) {return date && date.getTime() < (new Date().getTime()-86400000);}}"
                                            style="width: 100%"></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="考试时长(分钟)：" prop="examDuration">
                                <div v-if="mode === 'view'">{{form1data.examDuration}}</div>
                                <InputNumber style="width: 100%" v-model="form1data.examDuration" :min="1" v-else
                                             :max="120"></InputNumber>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="12">
                            <FormItem label="组卷方式：" prop="paperMode">
                                <div v-if="mode === 'view'">{{form1data.paperMode=='1'?'同类卷':form1data.paperMode=='2'?'AB卷':form1data.paperMode=='3'?'随机卷':''}}</div>
                                <Select v-model='form1data.paperMode' style="width: 100%;" placeholder="请选择考试范围" v-else
                                        clearable @change="handleChange">
                                    <Option v-for="item in dicMap.paperModeArr" :value="item.code" :key="item.code">{{
                                        item.name }}
                                    </Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="考试次数：" prop="examFrequency">
                                <div v-if="mode === 'view'">{{form1data.examFrequency}}</div>
                                <InputNumber style="width: 100%" v-model="form1data.examFrequency" v-else
                                             :min="1"></InputNumber>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="12">
                            <FormItem label="考试范围：" prop="examScope">
                                <div v-if="mode === 'view'">{{form1data.examScope=='1'?'公司全员':form1data.examScope=='2'?'指定分组':form1data.examScope=='3'?'选择配置':''}}</div>
                                <Select v-model='form1data.examScope' style="width: 100%;" placeholder="请选择考试范围" v-else
                                        clearable @on-change="handleChange">
                                    <Option v-for="item in dicMap.examScopeArr" :value="item.code" :key="item.code">{{
                                        item.lable }}
                                    </Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="考试分组：" v-if="form1data.examScope === '2'" prop="paperTeamId">
                                <div v-if="mode === 'view'">{{form1data.paperTeamName}}</div>
                                <Select v-model='form1data.paperTeamId' style="width: 100%;" placeholder="请选择考试分组" v-else @on-change="paperTeamChange">
                                    <Option v-for="item in dicMap.paperTeamArr" :value="item.id" :key="item.id">{{item.teamName }}
                                    </Option>
                                </Select>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row v-if="form1data.examScope === '3'" type="flex" justify="space-around" class="code-row-bg">
                        <Col span="24">
                            <FormItem label="考试人员：" prop="examiners">
                                <div v-if="mode === 'view'">{{form1data.examinersName}}</div>
                                <Input v-model="form1data.examinersName" type="textarea" v-else
                                       :autosize="{minRows:1,maxRows:5}"
                                       placeholder="请选择" readonly @click.native="examinerUserSelect"/>
                                <userDom :isButton="true" ref="userDom" :placeholderStr="'考试人员'"
                                         :selectData='setCurrentUserName'
                                         :singleChoice=false :ifUser="true" :rootOrgName="form1data.companyName"
                                         @setData='examinerUserSave'></userDom>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="8">
                            <FormItem label="总数(单选)：" prop="questionInfo">
                                <div v-if="mode === 'view'">{{form1data.radioCount}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.radioCount" disabled/>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="出题(单选)：" prop="paperRadio">
                                <div v-if="mode === 'view'">{{form1data.paperRadio}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperRadio" :min="0"
                                             :disabled="isDisabled1" :max="radioMax"></InputNumber>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="分值/每题(单选)：" prop="paperRadioNum">
                                <div v-if="mode === 'view'">{{form1data.paperRadioNum}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperRadioNum" :min="0"
                                             :disabled="isDisabled1"></InputNumber>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="8">
                            <FormItem label="总数(多选)：" prop="questionInfo">
                                <div v-if="mode === 'view'">{{form1data.checkboxCount}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.checkboxCount" disabled/>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="出题(多选)：" prop="paperCheckbox">
                                <div v-if="mode === 'view'">{{form1data.paperCheckbox}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperCheckbox" placeholder="请输入..."
                                             :min="0" :disabled="isDisabled2" :max="checkboxMax"></InputNumber>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="分值/每题(多选)：" prop="paperCheckboxNum">
                                <div v-if="mode === 'view'">{{form1data.paperCheckboxNum}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperCheckboxNum"
                                             placeholder="请输入..." :min="0" :disabled="isDisabled2"></InputNumber>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="8">
                            <FormItem label="总数(判断)：" prop="judgeCount">
                                <div v-if="mode === 'view'">{{form1data.judgeCount}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.judgeCount" disabled/>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="出题(判断)：" prop="paperJudge">
                                <div v-if="mode === 'view'">{{form1data.paperJudge}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperJudge" placeholder="请输入..."
                                             :min="0" :disabled="isDisabled3" :max="judgeMax"></InputNumber>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="分值/每题(判断)：" prop="paperJudgeNum">
                                <div v-if="mode === 'view'">{{form1data.paperJudgeNum}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.paperJudgeNum" placeholder="请输入..."
                                             :min="0" :disabled="isDisabled3"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row type="flex" justify="space-around" class="code-row-bg">
                        <Col span="8">
                            <FormItem label="试卷总分：" prop="fullMarks">
                                <div v-if="mode === 'view'">{{form1data.fullMarks}}</div>
                                <InputNumber v-else style="width: 100%" v-model="form1data.fullMarks" disabled/>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="合格分数：" prop="passNum">
                                <div v-if="mode === 'view'">{{form1data.passNum}}</div>
                                <InputNumber style="width: 100%" v-model="form1data.passNum" placeholder="请输入..." v-else
                                             :min="0"></InputNumber>
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem label="优秀分数：" prop="excellentNum">
                                <div v-if="mode === 'view'">{{form1data.excellentNum}}</div>
                                <InputNumber style="width: 100%" v-model="form1data.excellentNum" placeholder="请输入..." v-else
                                             :min="0"/>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button v-if="mode !== 'view'" class='ivu-btn-save' :loading="buttonLoading" @click="saveInfo">确定</Button>
                    <Button v-if="mode !== 'view'" class='ivu-btn-cancel' @click="closeModal">取消</Button>
                    <Button v-if="mode === 'view'" class='ivu-btn-cancel' @click="closeModal">关闭</Button>
                </div>
            </Modal>

            <Modal title="题库选择" :transfer=false footer-hide v-model="model2" :width=900>
                <Form ref="form2" :model="formInline2" :label-width="120">
                    <Row class="query-form">
                        <Col span="8">
                            <FormItem label="题库名称：" prop="bsaeQstInfo">
                                <Input v-model="formInline2.bsaeQstInfo"/>
                            </FormItem>
                        </Col>
                        <Col span="8" offset="8">
                            <Button @click="cancelBase" class="ivu-btn-reset">重置</Button>
                            <Button class="ivu-btn-query" icon="md-search" @click="queryBase">查询</Button>
                        </Col>
                    </Row>
                </Form>
                <Table :height="400" class="table" size="small" :loading="loading2"
                       highlight-row stripe border :columns="baseColumns" width="100%" :data="baseData">
                </Table>
                <Row style="margin-right:10px;">
                    <Col span="24">
                        <Page :total="pagedata.total1" :current="pagedata.currentPage1" :page-size="pagedata.pageSize1"
                              @on-page-size-change="pageSizeChange1" @on-change="pageChange1"
                              :page-size-opts="pageSizeArray" show-total show-sizer show-elevator/>
                    </Col>
                </Row>
            </Modal>
        </div>

        <paperUserList
                v-if="detailShow"
                :show="detailShow"
                :paper-id="paperId"
                :paper-info="paperInfo"
                :company-name="companyName"
                @close="close"
        />
    </Layout>
</template>

<script>
    import paperUserList from './paperUserList'
    import {Api} from '@/api'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import userDom from "@/components/input-user.vue";
    import {formatDate} from '@/tools/index'

    function countLevel() {
        if (this.form1data.examScope === '2') {
            // this.form1data.paperTeamId = ''
            this.form1data.examiners = ''
            this.form1data.examinersName = ''
            this.getPaperTeamByOrgId(this.form1data.companyId)
        }
    }

    export default {
        name: "paperList",
        components: {cascaderDom, userDom,paperUserList},
        data() {
            return {
                radioMax: 0,
                checkboxMax: 0,
                judgeMax: 0,
                maxNum: 100,
                isDisabled1: true,
                isDisabled2: true,
                isDisabled3: true,
                isUpdate: false,
                loading: true,
                loading2: true,
                formInline: {
                    paperInfo: '',
                },
                formInline2: {
                    bsaeQstInfo: ''
                },
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                    total1: 0,
                    pageSize1: 10,
                    currentPage1: 1
                },
                modal1: false,
                model2: false,
                buttonLoading: false,
                paperColumns: [
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '所属公司', align: 'center', minWidth: 200, key: 'companyName'},
                    {title: '试卷名称', minWidth: 180, align: 'center', key: 'paperInfo',tooltip:true},
                    {title: '试卷类型', align: 'center', minWidth: 100, key: 'paperType',tooltip:true},
                    {
                        title: '开始日期', align: 'center', minWidth: 100, key: 'examDateStart', render: (h, params) => {
                            if (!params.row['examDateStart']) return "";
                            return h('span', formatDate(new Date(params.row['examDateStart']), "yyyy-MM-dd"))
                        }
                    },
                    {
                        title: '结束日期', align: 'center', minWidth: 100, key: 'examDateEnd', render: (h, params) => {
                            if (!params.row['examDateEnd']) return "";
                            return h('span', formatDate(new Date(params.row['examDateEnd']), "yyyy-MM-dd"))
                        }
                    },
                    {title: '单选题', align: 'center', minWidth: 80, key: 'paperRadio'},
                    {title: '多选题', align: 'center', minWidth: 80, key: 'paperCheckbox'},
                    {title: '判断题', align: 'center', minWidth: 80, key: 'paperJudge'},
                    {
                        title: '状态', align: 'center', key: 'paperType', minWidth: 80,
                        render: (h, params) => {
                            return h('div', [
                                h('span', params.row.paperState == '0' ? '关闭' : params.row.paperState == '1' ? '开启' : '--')]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 280,
                        render: (h, params) => {
                            let flag = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId  || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? (params.row.paperState == '0'?'':'#F59A23') : '#d0d0d0',
                                        pointerEvents: flag ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            let state = params.row.paperState == 0 ? 1 : params.row.paperState == 1 ? 0 : 1;
                                            this.openPaperState(params.row, state);
                                        }
                                    }
                                }, params.row.paperState == 0 ? '开启' : params.row.paperState == 1 ? '关闭' : '开启'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.mode = 'view'
                                            this.getPaperById(params.row.paperId)
                                        }
                                    }
                                }, '查看'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? '' : '#d0d0d0',
                                        pointerEvents: flag ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            if (params.row.type == 0) {
                                                this.mode = 'edit'
                                                this.getPaperById(params.row.paperId)
                                            } else {
                                                this.$Message.error('当前试卷已有人作答，不可修改！');
                                            }

                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? 'red' : '#d0d0d0',
                                        pointerEvents: flag ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            if (params.row.type == 0) {
                                                this.deleteRow(params.row);
                                            } else {
                                                this.$Message.error('当前试卷已有人作答，不可删除！');
                                            }
                                        }
                                    }
                                }, '删除'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.detailShow = true
                                            this.paperId= params.row.paperId
                                            this.paperInfo= params.row.paperInfo
                                            this.companyName= params.row.companyName
                                        }
                                    }
                                }, '考试情况')
                            ]);
                        }
                    }
                ],
                paperData: [],
                form1data: {},
                ruleCustom: {
                    paperInfo: [{required: true, message: '请输入试卷名称', trigger: 'change'}],
                    paperType: [{required: true, message: '请输入试卷分类', trigger: 'change'}],
                    companyId: [{required: true, message: '请选择所属单位', trigger: 'change'}],
                    bsaeQstInfo: [{required: true, message: '请选择试题库', trigger: 'change'}],
                    // examDate: [{ required: true, message: '请选择考试日期', trigger: 'change',}],
                    examDate: [{
                        validator: (rule, value, callback) => {
                            if (this.form1data.examDate == undefined || this.form1data.examDate.length == 0 || this.form1data.examDate[0] == '') {
                                callback('请选择考试日期')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    examDuration: [{required: true, message: '请输入考试时长', trigger: 'change', type: 'number'}],
                    paperMode: [{required: true, message: '请选择组卷方式', trigger: 'change'}],
                    examFrequency: [{required: true, message: '请输入考试次数', trigger: 'change', type: 'number'}],
                    examScope: [{required: true, message: '请选择考试范围', trigger: 'change'}],
                    paperTeamId: [{required: true, message: '请选择考试分组', trigger: 'change'}],
                    examiners: [{required: true, message: '请添加考试人员', trigger: 'change'}],
                    passNum: [{required: true, message: '请输入合格分数', trigger: 'change', type: 'number'}],
                    excellentNum: [{required: true, message: '请输入优秀分数', trigger: 'change', type: 'number'}]
                },
                baseColumns: [
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '所属公司', align: 'center', key: 'companyName'},
                    {title: '题库名称', align: 'center', key: 'bsaeQstInfo'},
                    {title: '题库类型', align: 'center', key: 'bsaeQstState'},
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 80,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.form1data.passNum = 0;
                                            this.form1data.excellentNum = 0;
                                            this.getChoice(params.row);
                                        }
                                    }
                                }, '选择')
                            ]);
                        }
                    }
                ],
                baseData: [],
                companyId: '',
                mode:'',
                dicMap: {
                    paperModeArr: [{code: '1', name: '同类卷'}, {code: '2', name: 'AB卷'}, {code: '3', name: '随机卷'}],
                    examScopeArr: [{code: '1', lable: '公司全员'}, {code: '2', lable: '指定分组'}, {code: '3', lable: '选择配置'}],
                    paperTeamArr: []
                },
                setCurrentUserName: null,

                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                paperInfo: '',
                paperId: '',
                companyName: '',
                detailShow: false
            }
        },
        mounted() {
            this.companyId = sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight * 0.85 - this.$refs.table.$el.offsetTop - 40;
            this.query();
        },
        computed: {
            listenChange() {
                const {paperRadio, paperRadioNum, paperCheckbox, paperCheckboxNum, paperJudge, paperJudgeNum} = this.form1data
                return {paperRadio, paperRadioNum, paperCheckbox, paperCheckboxNum, paperJudge, paperJudgeNum}
            }
        },
        watch: {
            "modal1": function (qw, er) {
                if (qw && this.modal1) {
                    if (this.$refs.childOrg) {
                        setTimeout(() => {
                            this.$refs.childOrg.setCurrentOrg();
                        }, 100)
                    }
                } else {
                    if (this.$refs.childOrg) {
                        this.$refs.childOrg.resetCurrentOrg();
                    }
                    this.query()
                }
            },
            'form1data.companyId': countLevel,
            'form1data.examScope': countLevel,
            listenChange(val) {
                let countNum = 0
                if (val.paperRadio > 0) {
                    countNum += val.paperRadio * val.paperRadioNum
                }
                if (val.paperCheckbox > 0) {
                    countNum += val.paperCheckbox * val.paperCheckboxNum
                }
                if (val.paperJudge > 0) {
                    countNum += val.paperJudge * val.paperJudgeNum
                }
                this.$set(this.form1data, 'fullMarks', countNum)
            }
        },
        methods: {
            close() {
                this.detailShow = false
                // this.query()
            },
            query() {
                this.loading = true;
                let data = {
                    page: this.pagedata.currentPage,
                    rows: this.pagedata.pageSize,
                };
                if (this.formInline.companyId != null && this.formInline.companyId != undefined && this.formInline.companyId != '') {
                    this.formInline.orgId = this.formInline.companyId
                } else {
                    this.formInline.orgId = sessionStorage('userId').getObject('userId').companyId
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.paper + '/getPaperPageList', {
                    params: data,
                    paramsSerializer: params => {
                        return qs.stringify(params, {indices: false})
                    }
                }).then((res) => {
                    this.paperData = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                });
            },
            getPaperTeamByOrgId(companyId) {
                this.$http.get(Api.paper + '/getPaperTeamByOrgId/' + companyId).then((res) => {
                    if (res.data.status === 200) {
                        this.dicMap.paperTeamArr = res.data.data
                    }
                }).catch(e => {
                    this.$Message.error('请求失败');
                });
            },
            examinerUserSelect() {
                if (this.form1data.examiners) {
                    this.setCurrentUserName = []
                    let userIds = this.form1data.examiners.split(',')
                    let names = this.form1data.examinersName.split(',')
                    for (let k in userIds) {
                        this.setCurrentUserName.push({userId: userIds[k], name: names[k]})
                    }
                    this.$nextTick(() => {
                        this.$refs.userDom.setCurrentInfo();
                    })
                }
                this.$refs.userDom.openOrgModal();
                // setTimeout(() => {

                // }, 100)
            },
            examinerUserSave(data) {
                if (data.length > 0) {
                    let userIds = []
                    let userNames = []
                    data.forEach(v => {
                        userIds.push(v.userId);
                        userNames.push(v.name)
                    });
                    this.$nextTick(() => {
                        this.$set(this.form1data, 'examiners', userIds.join(','))
                        this.$set(this.form1data, 'examinersName', userNames.join(','))
                    })
                }
            },
            paperTeamChange(val){
                this.$set(this.form1data, 'paperTeamId', val)
            },
            handleChange(val) {
                if (val === '1') {
                    this.$set(this.form1data, 'paperTeamId', '')
                    this.$set(this.form1data, 'examiners', '')
                    this.$set(this.form1data, 'examinersName', '')
                } else if (val === '2') {
                    this.$set(this.form1data, 'examiners', '')
                    this.$set(this.form1data, 'examinersName', '')
                } else {
                    this.$set(this.form1data, 'paperTeamId', '')
                }
            },
            setOrgId(data) {
                this.form1data.companyId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1data.companyName = data;
            },
            setOrgId1(data) {
                this.formInline.companyId = data[data.length - 1];
            },
            setOrgName1(data) {
                this.formInline.companyName = data;
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            cancel() {
                this.formInline = {};
                this.query();
                this.$refs.queryOrgCascader.resetCurrentOrg();
            },
            addModel() {
                this.form1data = {
                    passNum: 0,//及格分
                    radioCount: this.radioMax,
                    paperRadio: 0,
                    paperRadioNum: 1,
                    checkboxCount: this.checkboxMax,
                    paperCheckbox: 0,
                    paperCheckboxNum: 2,
                    judgeCount: this.judgeMax,
                    paperJudge: 0,
                    paperJudgeNum: 1,
                    examDuration: 30,
                    examFrequency: 1,
                    excellentNum: 0,
                    fullMarks: 0,
                    companyId: sessionStorage('userId').getObject('userId').companyId,
                    companyName: sessionStorage('userId').getObject('userId').companyName,
                };
                this.mode = 'add'
                this.modal1 = true;
                this.isUpdate = false
            },
            openQuestionBase() {
                this.model2 = true;
                this.queryBase();
            },
            queryBase() {
                this.loading2 = true;
                let data = {
                    page: this.pagedata.currentPage1,
                    rows: this.pagedata.pageSize1,
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.formInline2)));
                this.$http.get(Api.questionBase, {
                    params: data,
                    paramsSerializer: params => {
                        return qs.stringify(params, {indices: false})
                    }
                }).then((res) => {
                    this.baseData = res.data.data.data;
                    this.pagedata.total1 = res.data.data.totalSize;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error('请求失败');
                });
            },
            pageChange1(pageNum) {
                this.pagedata.currentPage1 = pageNum;
                this.queryBase();
            },
            pageSizeChange1(pageSize) {
                this.pagedata.pageSize1 = pageSize;
                this.queryBase();
            },
            cancelBase() {
                this.formInline2 = {};
                this.queryBase();
            },
            renderViewDateArr(date) {
                if (!date || date[0] === "" || date[1] === "") {
                    return "";
                }
                return formatDate(new Date(date[0]), "yyyy-MM-dd")+' ~ '+
                        formatDate(new Date(date[1]), "yyyy-MM-dd");
            },
            getPaperById(paperId) {
                this.$http.get(Api.paper + '/getPaperById/' + paperId).then((res) => {
                    if (res.data.status === 200) {
                        const examDate = [res.data.data.examDateStart, res.data.data.examDateEnd]
                        this.$nextTick(() => {
                            this.$set(this.form1data, 'examDate', examDate)
                        })
                        this.form1data = res.data.data
                        this.getChoice(res.data.data)
                        this.modal1 = true;
                        this.isUpdate = false
                    } else {
                        this.$message.error(res.data.msg)
                    }
                })
            },
            getChoice(row) {
                this.form1data.bsaeQstId = row.bsaeQstId;
                this.form1data.bsaeQstInfo = row.bsaeQstInfo;
                this.form1data.radioCount = 0;
                this.form1data.checkboxCount = 0;
                this.form1data.judgeCount = 0;
                this.isDisabled1 = true;
                this.isDisabled2 = true;
                this.isDisabled3 = true;
                this.$http.get(Api.questionCount + '/' + row.bsaeQstId).then((res) => {
                    this.model2 = false;
                    for (let i = 0; i < res.data.data.length; i++) {
                        let count = res.data.data[i].questionInfo;
                        if (count == '' || count == undefined) {
                            count = 0;
                        }
                        res.data.data[i].questionType == 'radio' ? this.form1data.radioCount = count : res.data.data[i].questionType == 'checkbox' ? this.form1data.checkboxCount = count : res.data.data[i].questionType == 'judge' ? this.form1data.judgeCount = count : '--'
                    }
                    this.form1data.paperRadio = this.form1data.paperRadio < this.form1data.radioCount ? this.form1data.paperRadio : this.form1data.radioCount;
                    this.isDisabled1 = this.form1data.radioCount === 0;

                    this.form1data.paperCheckbox = this.form1data.paperCheckbox < this.form1data.checkboxCount ? this.form1data.paperCheckbox : this.form1data.checkboxCount;
                    this.isDisabled2 = this.form1data.checkboxCount === 0;

                    this.form1data.paperJudge = this.form1data.paperJudge < this.form1data.judgeCount ? this.form1data.paperJudge : this.form1data.judgeCount;
                    this.isDisabled3 = this.form1data.judgeCount === 0;
                    // if (this.form1data.radioCount === 0 ) {
                    //     this.form1data.radioCount = 0;
                    //     this.form1data.paperRadio = 0;
                    //     // this.form1data.paperRadioNum = 0;
                    // } else {
                    //     this.isDisabled1 = false;
                    // }
                    // if (this.form1data.checkboxCount === 0) {
                    //     this.form1data.checkboxCount = 0;
                    //     this.form1data.paperCheckbox = 0;
                    //     // this.form1data.paperCheckboxNum = 0;
                    // } else {
                    //     this.isDisabled2 = false;
                    // }
                    // if (this.form1data.judgeCount === 0) {
                    //     this.form1data.judgeCount = 0;
                    //     this.form1data.paperJudge = 0;
                    //     // this.form1data.paperJudgeNum = 0;
                    // } else {
                    //     this.isDisabled3 = false;
                    // }
                    this.radioMax = this.form1data.radioCount;
                    this.checkboxMax = this.form1data.checkboxCount;
                    this.judgeMax = this.form1data.judgeCount;


                }).catch(e => {
                    this.$Message.error('请求失败');
                });
            },
            saveInfo() {
                this.$refs['formCustom'].validate((valid) => {
                    if (valid) {
                        if (this.form1data.passNum === 0) {
                            this.$Message.error('合格分数不能为0！')
                        } else if (this.form1data.excellentNum === 0) {
                            this.$Message.error('优秀分数不能为0！')
                        } else if (this.form1data.paperRadio === 0 && this.form1data.paperCheckbox === 0 && this.form1data.paperJudge === 0) {
                            this.$Message.error('出题总数量不能为0！')
                        } else {
                            this.buttonLoading = true
                            this.form1data.examDateStart = this.form1data.examDate[0]
                            this.form1data.examDateEnd = this.form1data.examDate[1]
                            this.$http.post(Api.paper + '/savePaper', this.form1data).then((res) => {
                                if (res.data.status == 200) {
                                    this.query();
                                    this.$Message.success({
                                        content: '成功',
                                        duration: 4
                                    });
                                    this.closeModal();
                                } else {
                                    this.$Message.error(res.data.msg)
                                }
                                this.buttonLoading = false
                            }).catch(e => {
                                this.buttonLoading = false
                                this.$Message.error({
                                    content: '请求失败',
                                    duration: 4
                                });
                            });
                        }
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            closeModal() {
                this.form1data = {};
                this.isDisabled1 = true;
                this.isDisabled2 = true;
                this.isDisabled3 = true;
                this.modal1 = false;
            },
            deleteRow(row) {
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该试题</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.paper + '/deletePaperById/' + row.paperId, {
                            params: {
                                paperId: row.paperId
                            }
                        }).then((res) => {
                            this.$Message.success({content: '确认成功', duration: 4});
                            this.modal1 = false;
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            openPaperState(paper, state) {
                this.$http.post(Api.paper + '/onOffPaper/' + paper.paperId + '/' + state, {}).then((res) => {
                    this.$Message.success({
                        content: '状态设置成功',
                        duration: 4
                    });
                    this.query();
                }).catch(e => {
                    this.$Message.error({
                        content: '状态设置失败',
                        duration: 4
                    });
                });
            },
            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 32; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
                let uuid = s.join("");
                return uuid
            }
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';

</style>
